﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Weibo2Sfdc.SfWeb;
using System.Threading;
using System.Web;
using System.Web.UI.WebControls;
using System.Collections;
using mshtml;
using System.Reflection;

namespace Weibo2Sfdc
{
    public partial class MainForm : Form
    {
        private ArrayList keywordCategoryList; //获取category列表
        private Dictionary<string, string> categoryMap = new Dictionary<string,string>(); //其中key为category的Name，value为category的Id
        private Dictionary<string, ArrayList> lsKeywordListMap; //其中key为category的Id,value为TRIXPRO_WB__Keyword__c的Arraylist；

        private int keywordsnum = 1; //查询的关键字数量。当>1时，数据直接上传，不提示； 当=1时，提示是否上传。
        private int syncNum = 0;//记录已经上传了几个关键字

        public MainForm()
        {
            InitializeComponent();
        }

        public WeiboEnquiryEngine WeiboEnquiryEngine
        {
            get
            {
                return WeiboEnquiryEngine.GetInstance();
            }
        }

        public SyncEngine SyncEngine
        {
            get
            {
                return SyncEngine.GetInstance();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EnquiryDone(object sender, EventArgs e)
        {
            //start to upload to sfdc
            
            web_main.Tag = "run"; //下一个关键字接着查询
            if (keywordsnum == 1)
            { //一个关键字查询时，上传之前询问
                if (MessageBox.Show("Are you sure upload to salesforce", "", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    SyncEngine.StartSync();
                    MessageBox.Show("Sync Completed");
                }
            }
            else
            {//多个关键字，直接上传，不询问                
                SyncEngine.StartSync();
                syncNum++;
                //System.Console.WriteLine("keywordsnum/syncNum=" + keywordsnum + "/" + syncNum);
                if (syncNum == keywordsnum)
                { //上传次数和关键字次数一样，提示上传完成
                    MessageBox.Show("Sync Completed");
                }
            }
            
        }

        private void btn_go_Click(object sender, EventArgs e)
        {
            web_main.Navigate(txt_url.Text);
        }
        /// <summary>
        /// on main form load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {

            web_main.Navigate("http://s.weibo.com/");


            // Show Login User Config
            this.Show();
            // check sfdc user and weibo user
            String sf_usr = Properties.Settings.Default.SfdcUsername;
            String sf_pwd = Properties.Settings.Default.SfdcPassword;
            String wb_usr = Properties.Settings.Default.WeiboUsername;
            String wb_pwd = Properties.Settings.Default.WeiboPassword;

            if (String.IsNullOrEmpty(sf_usr) || String.IsNullOrEmpty(sf_pwd) ||
                String.IsNullOrEmpty(wb_usr) || String.IsNullOrEmpty(wb_pwd))
            {
                MessageBox.Show("系统检测，你还没有配置用户信息！");

                UserConfigForm usrConfig = new UserConfigForm( web_main );
                usrConfig.StartPosition = FormStartPosition.CenterParent;
                usrConfig.ShowDialog();
            }

            //cmb_keyword_catalog.SelectedIndex = 0;
            //set webbrowser
            web_main.Tag = "";
            WeiboEnquiryEngine.web_main = web_main;
            //set engine done action.
            WeiboEnquiryEngine.Done += new EventHandler(this.EnquiryDone);

            //从salesforce获取关键字
            getKeywords2Show();
            
        }

        //获取关键字类型，关键字列表，并展示
        private void getKeywords2Show() {

            //获取category列表
            //获取category的Map,其中key为category的Name，value为category的Id
            //获取keyword的Map,其中key为category的Id,value为TRIXPRO_WB__Keyword__c的Arraylist；

            //登录salesforce
            SfConnection conn = new SfConnection();


            // check sfdc login
            String sfdc_usr = Properties.Settings.Default.SfdcUsername;
            String sfdc_pwd = Properties.Settings.Default.SfdcPassword;

            if (String.IsNullOrEmpty(sfdc_usr) || String.IsNullOrEmpty(sfdc_pwd))
            {
                MessageBox.Show("初始化失败.\nSalesforce 账号或密码为空!");
                UserConfigForm usrConfig = new UserConfigForm( web_main );
                usrConfig.StartPosition = FormStartPosition.CenterParent;
                usrConfig.SelectTab("SfdcUserConfig");
                usrConfig.ShowDialog();

            }
            else
            {
                conn.login(sfdc_usr, sfdc_pwd);

                //获取Category的列表
                keywordCategoryList = conn.getKeywordCategoryList();
                categoryMap.Clear();
                for (int i = 0; i < keywordCategoryList.Count; i++)
                {
                    TRIXPRO_WB__Keyword_Category__c c = (TRIXPRO_WB__Keyword_Category__c)keywordCategoryList[i];
                    this.categoryMap.Add(c.Name, c.Id);
                }

                //获取keyword的Map,其中key为category的id,value为TRIXPRO_WB__Keyword__c的ArrayList
                lsKeywordListMap = conn.getKeywordListMap();

                //展示
                showCategoryList(keywordCategoryList);
                TRIXPRO_WB__Keyword_Category__c kcc = (TRIXPRO_WB__Keyword_Category__c)keywordCategoryList[0];
                showKeywordListByCategoryId(kcc.Id, lsKeywordListMap);
            }
        }
 

        private void lnk_show_detail_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            WeiboEnquiryDetail frm = new WeiboEnquiryDetail();
            //set weibo enquiry resoult
            frm.ShowDialog();
        }

        /// <summary>
        /// select all keyword
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnk_select_all_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (int i = 0; i < lst_keyword.Items.Count; i++)
            {
                lst_keyword.SetItemChecked(i, true);
            }
        }
        /// <summary>
        /// clear all keyword
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lnk_unselect_all_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            for (int i = 0; i < lst_keyword.Items.Count; i++)
            {
                lst_keyword.SetItemChecked(i, false);
            }
        }

        private void web_main_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            
            //WeiboEnquiryEngine.DocumentCompleted(sender,e);

            //由于微博内容有多页时，此事件触发后，有可能还会通过js采用ajax方式载入数据，因此用定时器暂停一下再读取数据
            timer1.Interval = 3000;
            timer1.Enabled = true;
        }

        //开始根据关键字查询微博内容
        private void sync2sfdc_Click(object sender, EventArgs e)
        {
            //开始查询微博
            //WeiboEnquiryEngine.Start();
            string categoryName = this.cmb_keyword_catalog.SelectedItem.ToString();
            string categoryId = this.categoryMap[categoryName];

            int n = this.lst_keyword.CheckedIndices.Count;
            
            if (n < 1) {
                MessageBox.Show("请先选择关键字");
                return;
            }

            keywordsnum = n;//保留本次查询的关键字数量。用于判断上传之前是否提示。
            syncNum = 0;//已经上传的关键字微博重置为0

            ArrayList listKeywords = new ArrayList();

            foreach (object itemChecked in lst_keyword.CheckedItems)
            {
                ListItem item = (ListItem)itemChecked;
                TRIXPRO_WB__Keyword__c kwc = new TRIXPRO_WB__Keyword__c();
                kwc.TRIXPRO_WB__Keyword_Category__c = categoryId;
                kwc.Id = item.Value;
                kwc.Name = item.Text;
                listKeywords.Add(kwc);
                //MessageBox.Show(kwc.Id + " / " + kwc.Name + " / " +kwc.TRIXPRO_WB__Keyword_Category__c);
            }

            //根据关键字列表读取数据
            //WeiboEnquiryEngine.Start2(listKeywords);
            WeiboEnquiryEngine.Start3(listKeywords); //通过多线程启动调度程序，可以同时查询多个关键字并上传
        }

        private void cmb_time_period_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        //显示Category下拉列表
        private void showCategoryList(ArrayList keywordCategoryList)
        {
            this.cmb_keyword_catalog.Items.Clear();
            int n = keywordCategoryList.Count;
            for (int i = 0; i < n; i++)
            {
                TRIXPRO_WB__Keyword_Category__c c = (TRIXPRO_WB__Keyword_Category__c)keywordCategoryList[i];
                this.cmb_keyword_catalog.Items.Add(c.Name);
            }
            cmb_keyword_catalog.SelectedIndex = 0; //默认选中第1个
        }

        //根据CategoryId更新关键字列表
        private void showKeywordListByCategoryId(String categoryId, Dictionary<string,ArrayList> lsKeywordListMap)
        {           
            lst_keyword.Items.Clear();
            ArrayList lskeyword = lsKeywordListMap[categoryId]; //根据category Id获取对应的keyword列表
            int n = lskeyword.Count;
            for (int i = 0; i < n; i++)
            {
                TRIXPRO_WB__Keyword__c c = (TRIXPRO_WB__Keyword__c)lskeyword[i];
                ListItem item=new ListItem();
                item.Value = c.Id;
                item.Text = c.Name;
                lst_keyword.Items.Add(item);
            }

            //默认都选中
            for (int i = 0; i < lst_keyword.Items.Count; i++)
            {
                lst_keyword.SetItemChecked(i, true);
            }

        }

        //关键字分类改变时
        private void cmb_keyword_catalog_SelectedValueChanged(object sender, EventArgs e)
        {
            //当前选中的文本
            string selectCmbText = this.cmb_keyword_catalog.SelectedItem.ToString();
           // string categoryId = getCategoryIdByText(selectCmbText); //根据
            if (categoryMap == null) { return; }
            string selectCategoryId = this.categoryMap[selectCmbText];
            showKeywordListByCategoryId(selectCategoryId, lsKeywordListMap);


        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            //初始化关键字
            getKeywords2Show();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            timer1.Enabled = false;
            WeiboEnquiryEngine.DocumentCompleted(sender, null);
        }

        private void txt_url_TextChanged(object sender, EventArgs e)
        {

        }

        private void cmb_keyword_catalog_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void grp_top_Enter(object sender, EventArgs e)
        {

        }

        private void btn_WbUserConfig_Click(object sender, EventArgs e)
        {
            UserConfigForm usrConfigForm = new UserConfigForm(web_main);
            usrConfigForm.StartPosition = FormStartPosition.CenterScreen;
            usrConfigForm.ShowDialog();
        }

        private void btn_Wb_WeiboLogin_Click(object sender, EventArgs e)
        {
            // check weibo is login or not
            IHTMLDocument2 vDocument = web_main.Document.DomDocument as IHTMLDocument2;
            IHTMLWindow2 vWindow = (IHTMLWindow2)vDocument.parentWindow;

            vWindow.execScript("var WEIBO2SFDC_islogin =  $CONFIG['islogin'];", "JavaScript");
            Object islogin = vWindow.GetType().InvokeMember(
                                                    "WEIBO2SFDC_islogin", BindingFlags.GetProperty,
                                                     null, vWindow, new object[] { });

            web_main.Navigate( "http://weibo.com/login" );

            WBAutoLogin login = new WBAutoLogin();

            if (islogin.ToString() == "0" && web_main.StatusText == "Done")
            {
                login.AutoLoginWeibo(web_main);
            }
            else if (islogin.ToString() == "1" )
            {
                MessageBox.Show("你已经登陆!");
            }
            else 
            {
                MessageBox.Show("登陆失败!");
            }

        }

    }


    public class SfConnection
    {
        SforceService SfdcBinding = null; //连接。 如何关闭？？？

        //关键字的Map,key为id(category的ID),value为一个TRIXPRO_WB__Keyword__c对象的List
        private Dictionary<string, ArrayList> keywordListMap = new Dictionary<string, ArrayList>();

        //TRIXPRO_WB__Keyword_Category__c的Map ，key为id,value为一个TRIXPRO_WB__Keyword_Category__c对象
        private Dictionary<string, TRIXPRO_WB__Keyword_Category__c> catrgoryMap = new Dictionary<string, TRIXPRO_WB__Keyword_Category__c>();


        //构造函数
        public SfConnection()
        {
        }

        /// <summary>
        /// 登录salesforce
        /// </summary>
        public void login(string userName, string password)
        {
            //string userName;
            //string password;
            //userName = "user@weibo.dev";
            //password = "123456";
            //SforceService SfdcBinding = null;

            LoginResult CurrentLoginResult = null;
            SfdcBinding = new SforceService();
            try
            {
                CurrentLoginResult = SfdcBinding.login(userName, password);
            }
            catch (System.Web.Services.Protocols.SoapException e1)
            {
                // This is likley to be caused by bad username or password
                SfdcBinding = null;
                throw (e1);
            }
            catch (Exception e2)
            {
                // This is something else, probably comminication
                SfdcBinding = null;
                throw (e2);
            }

            //Change the binding to the new endpoint
            SfdcBinding.Url = CurrentLoginResult.serverUrl;

            //Create a new session header object and set the session id to that returned by the login
            SfdcBinding.SessionHeaderValue = new SessionHeader();
            SfdcBinding.SessionHeaderValue.sessionId = CurrentLoginResult.sessionId;
        }

        /// <summary>
        /// 关闭登录
        /// </summary>
        public void logout() {
            if (SfdcBinding != null) {
                SfdcBinding.logout();
            }
        }

        /// <summary>
        /// 获取Keyword的Map,其中key为Category的Id, value为Keyword的ArrayList
        /// </summary>
        /// <returns></returns>
        public Dictionary<string, ArrayList> getKeywordListMap()
        {
            keywordListMap = new Dictionary<string, ArrayList>();
            ArrayList cateList = getKeywordCategoryList();  //category列表
            ArrayList keywordList = getAllActiveKeywordsList(); //keyword列表

            int n = cateList.Count;
            if(n>0){
                for (int i = 0; i < n; i++) { 
                    TRIXPRO_WB__Keyword_Category__c c=(TRIXPRO_WB__Keyword_Category__c)cateList[i];
                    keywordListMap.Add(c.Id,new ArrayList());
                }

                int m = keywordList.Count;
                for (int j = 0; j < m; j++) {
                    TRIXPRO_WB__Keyword__c k = (TRIXPRO_WB__Keyword__c)keywordList[j];
                    ArrayList lsCate = keywordListMap[k.TRIXPRO_WB__Keyword_Category__c];
                    if (lsCate != null) {
                        lsCate.Add(k);                        
                    }
                }
                            
            }

            return keywordListMap;
        }


        public ArrayList getKeywordCategoryList()
        {
            if (SfdcBinding == null)
            {
                System.Console.WriteLine("请先登录.");
                return null;
            }

            String SOQL = "";
            //LoginResult CurrentLoginResult = null;
            QueryResult queryResult = null;

            SOQL = "select Name, TRIXPRO_WB__Description__c,Id  from TRIXPRO_WB__Keyword_Category__c  where TRIXPRO_WB__Active__c = true order by Name asc";
            queryResult = SfdcBinding.query(SOQL);

            ArrayList kccList = new ArrayList();

            if (queryResult.size > 0)
            {
                for (int i = 0; i < queryResult.size; i++)
                {
                    TRIXPRO_WB__Keyword_Category__c kcc = (TRIXPRO_WB__Keyword_Category__c)queryResult.records[i];
                    kccList.Add(kcc);
                    //System.Console.WriteLine(kcc.Name + " / " + kcc.Id);
                }

            }

            return kccList;
        }

        /// <summary>
        /// 读取所有Keyword List
        /// </summary>
        /// <returns></returns>
        private ArrayList getAllActiveKeywordsList()
        {
            if (SfdcBinding == null)
            {
                System.Console.WriteLine("请先登录.");
                return null;
            }

            String SOQL = "";
            //LoginResult CurrentLoginResult = null;
            QueryResult queryResult = null;
            SOQL = "select Name, Id, TRIXPRO_WB__Keyword_Category__c from TRIXPRO_WB__Keyword__c  where TRIXPRO_WB__Active__c = true order by Name asc";
            queryResult = SfdcBinding.query(SOQL);

            ArrayList kccList = new ArrayList();

            if (queryResult.size > 0)
            {
                for (int i = 0; i < queryResult.size; i++)
                {
                    TRIXPRO_WB__Keyword__c kcc = (TRIXPRO_WB__Keyword__c)queryResult.records[i];
                    kccList.Add(kcc);
                    //System.Console.WriteLine("Here");
                    //System.Console.WriteLine(kcc.Name + " / " + kcc.Id );
                }
            }

            return kccList;
        }


    }
}
